#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    printf("testexec begin...\n");

    pid_t id =fork();
    
    if(id == 0)
    {
        sleep(2);
        putenv("HHHH=111111111111111111");  // 更新新环境变量到就环境变量中

        // 父进程本身就有一堆环境变量，从bash中来
        //char *const envp[] =
        //{
        //    (char*)"HAHA=111111",
        //    (char*)"HEHE=222222",
        //    NULL
        //};
        char *const argv[] = 
        {
            (char*)"mypragma",
            (char*)"-a",
            (char*)"-b",
            NULL
            //(char*)"ls",
            //(char*)"-a",
            //(char*)"-l",
            //(char*)"--color",
            //NULL
        };

        // 调用自己，可以替换其他语言
        extern char**environ;
        printf("child pid: %d\n", getpid());
        execvpe("./mypragma", argv, environ);
        //execvpe("./mypragma", argv, envp);
        //execl("/usr/bin/python3", "python3", "test.py", NULL);
        //execl("/usr/bin/bash", "bash", "test.sh", NULL);
        //execl("./mypragma", "mypragma", NULL);

        // 调用ls等系统指令
        // child
        //execvp("ls", argv);
        //execv("/usr/bin/ls", argv);
        //execlp("top", "top", NULL);
        //execl("/usr/bin/ls", "ls", "-a", "-l", NULL);
        exit(1);
    }

    // father
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);    //block
    if(rid > 0)
    {
        printf("father wait success, child exit code: %d\n", WEXITSTATUS(status));
    }

    printf("testexec end...\n");

    return 0;
}
